//
//  GruphotoAppDelegate.m
//  Gruphoto
//
//  Created by Thao Nguyen Huy on 1/3/13.
//  Copyright (c) 2013 CNC Software. All rights reserved.
//

#import "GruphotoAppDelegate.h"
#import "HomeViewController.h"

@implementation GruphotoAppDelegate
@synthesize currentLocation, locationManager;
@synthesize loggedInUser;

+ (GruphotoAppDelegate *)sharedDelegate {
    static GruphotoAppDelegate *sharedDelegate;
    @synchronized (self) {
        if (sharedDelegate == nil) {
            sharedDelegate = (GruphotoAppDelegate *)[[UIApplication sharedApplication] delegate];
        }
    }
    return sharedDelegate;
}

- (void)dealloc {
    self.loggedInUser = nil;
    self.locationManager = nil;
    self.currentLocation = nil;
    [_window release];
    [super dealloc];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    NSLog(@"Names: %@\n%@", [UIFont fontNamesForFamilyName:@"Myriad Pro"], [UIFont fontNamesForFamilyName:@"Helvetica Neue"]);
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
    // Override point for customization after application launch.
    
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
    
    self.locationManager = [[[CLLocationManager alloc] init] autorelease];
    locationManager.delegate = self;
    locationManager.distanceFilter = kCLDistanceFilterNone;
    locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;
    [locationManager startUpdatingLocation];
    
    [FBProfilePictureView class];
    
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
    NSString *nibName = @"HomeViewController";
    if ([Global isIphone5]) {
        nibName = @"HomeViewController-568h";
    }
    HomeViewController *homeViewController = [[HomeViewController alloc] initWithNibName:nibName
                                                                                  bundle:nil];
    UINavigationController *homeNavigator = [[UINavigationController alloc] initWithRootViewController:homeViewController];
    [homeViewController release];
    self.window.rootViewController = homeNavigator;
    [homeNavigator release];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];    
    return YES;
}

- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)devToken {
    NSString *_deviceToken = [devToken description];
	_deviceToken = [_deviceToken stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
	_deviceToken = [_deviceToken stringByReplacingOccurrencesOfString:@" " withString:@""];
    [[NSUserDefaults standardUserDefaults] setObject:_deviceToken forKey:kDeviceToken];
}

- (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err {
    NSString *_deviceToken = @"27746997cd56f6d576dafaf0851eba2fee2b3e4e";
    [[NSUserDefaults standardUserDefaults] setObject:_deviceToken forKey:kDeviceToken];
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // FBSample logic
    // We need to properly handle activation of the application with regards to SSO
    //  (e.g., returning from iOS 6.0 authorization dialog or from fast app switching).
    [FBSession.activeSession handleDidBecomeActive];
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // FBSample logic
    // if the app is going away, we close the session object; this is a good idea because
    // things may be hanging off the session, that need releasing (completion block, etc.) and
    // other components in the app may be awaiting close notification in order to do cleanup
    [FBSession.activeSession close];
}

- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation {
    // FBSample logic
    // We need to handle URLs by passing them to FBSession in order for SSO authentication
    // to work.
    return [FBSession.activeSession handleOpenURL:url];
}

#pragma mark - Facebook activity
- (void)sessionStateChanged:(FBSession *)session
                      state:(FBSessionState)state
                      error:(NSError *)error
{
    NSLog(@"state changed to %d", state);
    // FBSample logic
    // Any time the session is closed, we want to display the login controller (the user
    // cannot use the application unless they are logged in to Facebook). When the session
    // is opened successfully, hide the login controller and show the main UI.
    switch (state) {
        case FBSessionStateOpen: {
            [[NSNotificationCenter defaultCenter] postNotificationName:GPFacebookSessionDidOpenedNotification
                                                                object:session];
            // FBSample logic
            // Pre-fetch and cache the friends for the friend picker as soon as possible to improve
            // responsiveness when the user tags their friends.
            FBCacheDescriptor *cacheDescriptor = [FBFriendPickerViewController cacheDescriptor];
            [cacheDescriptor prefetchAndCacheForSession:session];
        }
            break;
        case FBSessionStateClosed: {
            // FBSample logic
            // Once the user has logged out, we want them to be looking at the root view.
            
            [FBSession.activeSession closeAndClearTokenInformation];

        }
            break;
        case FBSessionStateClosedLoginFailed: {
            // if the token goes invalid we want to switch right back to
            // the login view, however we do it with a slight delay in order to
            // account for a race between this and the login view dissappearing
            // a moment before

        }
            break;
        default:
            break;
    }
    
    [[NSNotificationCenter defaultCenter] postNotificationName:GPFacebookSessionStateChangedNotification
                                                        object:session];
    
    if (error) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"Error: %@", [GruphotoAppDelegate FBErrorCodeDescription:error.code]]
                                                            message:error.localizedDescription
                                                           delegate:nil
                                                  cancelButtonTitle:@"OK"
                                                  otherButtonTitles:nil];
        [alertView show];
        [alertView release];
    }
}

- (BOOL)openSessionWithAllowLoginUI:(BOOL)allowLoginUI {
    return [FBSession openActiveSessionWithReadPermissions:nil
                                              allowLoginUI:allowLoginUI
                                         completionHandler:^(FBSession *session, FBSessionState state, NSError *error) {
                                             [self sessionStateChanged:session state:state error:error];
                                         }];
}

+ (NSString *)FBErrorCodeDescription:(FBErrorCode) code {
    switch(code){
        case FBErrorInvalid :{
            return @"FBErrorInvalid";
        }
        case FBErrorOperationCancelled:{
            return @"FBErrorOperationCancelled";
        }
        case FBErrorLoginFailedOrCancelled:{
            return @"FBErrorLoginFailedOrCancelled";
        }
        case FBErrorRequestConnectionApi:{
            return @"FBErrorRequestConnectionApi";
        }case FBErrorProtocolMismatch:{
            return @"FBErrorProtocolMismatch";
        }
        case FBErrorHTTPError:{
            return @"FBErrorHTTPError";
        }
        case FBErrorNonTextMimeTypeReturned:{
            return @"FBErrorNonTextMimeTypeReturned";
        }
        case FBErrorNativeDialog:{
            return @"FBErrorNativeDialog";
        }
        default:
            return @"[Unknown]";
    }
}

#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    self.currentLocation = newLocation;
}

#pragma mark - MBProgressHUDDelegate & methods
#pragma mark - MBProgressHUD
- (void)showHUDWithStatus:(NSString *)status {
	progressHud = [[MBProgressHUD alloc] initWithView:self.window];
	[self.window addSubview:progressHud];
    progressHud.dimBackground = YES;
	progressHud.delegate = self;
	progressHud.labelText = status;
    [progressHud show:YES];
}

- (void)setHUDStatus:(NSString *)status {
    if (progressHud != nil) {
        progressHud.labelText = status;
    }
    else {
        progressHud = [[MBProgressHUD alloc] initWithView:self.window];
        [self.window addSubview:progressHud];
        progressHud.dimBackground = YES;
        progressHud.delegate = self;
        progressHud.labelText = status;
        [progressHud show:YES];        
    }
}

- (void)hideHUD {
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    [progressHud hide:YES];
}

- (void)hudWasHidden:(MBProgressHUD *)hud {
	// Remove HUD from screen when the HUD was hidded
	[progressHud removeFromSuperview];
	[progressHud release];
	progressHud = nil;
}

@end
